<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="index.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        canvas {
            margin: 50px auto 0;
            display: block;
            background: yellow;
        }
    </style>
</head>
<body>
<canvas id="canvas" width="400" height="400">
    此浏览器不支持canvas
</canvas>
</body>
</html>
<script>
    const ctx = document.getElementById('canvas')
    const gl = ctx.getContext('webgl')

    const VERTEX_SHADER_SORUCE = `
    attribute vec4 aPosition;
    void main(){
      gl_Position = aPosition;
      gl_PointSize = 10.0;
    }
  `;
    // uniform 类型声明为vec2 设置是vec4
    // uniform vec2 uColor;
    // gl_FragColor = vec4(uColor.r,uColor.g,0.0,1.0);
    // 若使用uniform1f时声明类型需为float
    const FRAGEMNT_SHADER_SOURCE = `
    precision mediump float;
    uniform vec2 uColor;
    void main(){
      gl_FragColor = vec4(uColor.r,uColor.g,0.0,1.0);
    }
  `;
    // 封装后
    const program = initShader(gl, VERTEX_SHADER_SORUCE, FRAGEMNT_SHADER_SOURCE)
    const aPosition = gl.getAttribLocation(program, 'aPosition')
    const uColor = gl.getUniformLocation(program,'uColor')

    // gl.vertexAttrib1f(aPosition, 0.0)
    // // 执行绘制
    // gl.drawArrays(gl.POINTS, 0, 1);

    ctx.onclick = function (ev) {
        // 坐标
        const x = ev.clientX
        const y = ev.clientY

        const domPosition = ev.target.getBoundingClientRect()
        console.log(domPosition, ctx.offsetTop, ctx.offsetLeft)
        // 当前鼠标在画布上点击的位置
        const domx = x - domPosition.left
        const domy = y - domPosition.top
        // 转换为-1——1的区间使用，坐标系
        const halfWidth = ctx.offsetWidth / 2
        const halfHeight = ctx.offsetHeight / 2
        const clickX = (domx - halfWidth) / halfWidth
        const clickY = (halfHeight - domy) / halfHeight
        console.log(clickX, clickY)
        gl.vertexAttrib2f(aPosition, clickX, clickY)
        gl.uniform2f(uColor,clickX,clickY)

        // 执行绘制
        gl.drawArrays(gl.POINTS, 0, 1);
    }

</script>
